package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"month2/C/rpc_C/model/es"

	"month2/C/rpc_C/internal/svc"
	"month2/C/rpc_C/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSearchGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSearchGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSearchGoodsLogic {
	return &EsSearchGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *EsSearchGoodsLogic) EsSearchGoods(in *order.EsSearchGoodsRequest) (*order.GoodsListResponse, error) {
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if in.Keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsName": in.Keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := es.Es.Search(
		es.Es.Search.WithContext(context.Background()),
		es.Es.Search.WithIndex("goods"),
		es.Es.Search.WithBody(&buf),
		es.Es.Search.WithTrackTotalHits(true),
		es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	r := map[string]interface{}{}
	json.NewDecoder(res.Body).Decode(&r)
	var list []*order.GoodsList
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})
		list = append(list, &order.GoodsList{
			GoodsName:  source["GoodsName"].(string),
			GoodsPrice: float32(source["GoodsPrice"].(float64)),
			GoodsNum:   int64(source["GoodsNum"].(float64)),
			GoodsImg:   source["GoodsImg"].(string),
			LikeCount:  int64(source["LikeCount"].(float64)),
		})
	}
	return &order.GoodsListResponse{List: list}, nil
}
